<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑试题' : '新增试题'"
    width="80%"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="question-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="试题标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入试题标题"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="题型" prop="type">
            <el-select v-model="form.type" placeholder="请选择题型" style="width: 100%">
              <el-option
                v-for="type in questionTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="学科" prop="subjectId">
            <el-select
              v-model="form.subjectId"
              placeholder="请选择学科"
              style="width: 100%"
              @change="handleSubjectChange"
            >
              <el-option
                v-for="subject in subjects"
                :key="subject.id"
                :label="subject.name"
                :value="subject.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分类" prop="categoryId">
            <el-select
              v-model="form.categoryId"
              placeholder="请选择分类"
              style="width: 100%"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="难度" prop="difficulty">
            <el-rate v-model="form.difficulty" show-text />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分值" prop="score">
            <el-input-number
              v-model="form.score"
              :min="1"
              :max="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="试题内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          placeholder="请输入试题内容"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>

      <!-- 选择题选项 -->
      <div v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(form.type)">
        <el-form-item label="选项设置">
          <div class="options-container">
            <div
              v-for="(option, index) in form.options"
              :key="index"
              class="option-item"
            >
              <el-checkbox
                v-if="form.type === 'MULTIPLE_CHOICE'"
                v-model="option.correct"
                class="option-checkbox"
              />
              <el-radio
                v-else
                v-model="correctAnswer"
                :label="index"
                class="option-radio"
              />
              <el-input
                v-model="option.content"
                :placeholder="`选项 ${String.fromCharCode(65 + index)}`"
                class="option-input"
              />
              <el-button
                v-if="form.options.length > 2"
                type="danger"
                size="small"
                @click="removeOption(index)"
                icon="Delete"
              />
            </div>
            <el-button
              v-if="form.options.length < 6"
              type="primary"
              size="small"
              @click="addOption"
              icon="Plus"
            >
              添加选项
            </el-button>
          </div>
        </el-form-item>
      </div>

      <!-- 判断题答案 -->
      <div v-if="form.type === 'TRUE_FALSE'">
        <el-form-item label="正确答案" prop="answer">
          <el-radio-group v-model="form.answer">
            <el-radio label="true">正确</el-radio>
            <el-radio label="false">错误</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 填空题和问答题答案 -->
      <div v-if="['FILL_BLANK', 'ESSAY'].includes(form.type)">
        <el-form-item label="参考答案" prop="answer">
          <el-input
            v-model="form.answer"
            type="textarea"
            :rows="3"
            placeholder="请输入参考答案"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </div>

      <el-form-item label="解析">
        <el-input
          v-model="form.explanation"
          type="textarea"
          :rows="3"
          placeholder="请输入试题解析（可选）"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { questionApi } from '@/api/questions'

interface Props {
  modelValue: boolean
  question?: any
  subjects: any[]
  categories: any[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  question: null
})

const emit = defineEmits<Emits>()

const formRef = ref()
const loading = ref(false)
const correctAnswer = ref(0)

const questionTypes = [
  { value: 'SINGLE_CHOICE', label: '单选题' },
  { value: 'MULTIPLE_CHOICE', label: '多选题' },
  { value: 'TRUE_FALSE', label: '判断题' },
  { value: 'FILL_BLANK', label: '填空题' },
  { value: 'ESSAY', label: '问答题' }
]

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.question?.id)

const form = reactive({
  id: null,
  title: '',
  type: 'SINGLE_CHOICE',
  content: '',
  subjectId: undefined,
  categoryId: undefined,
  difficulty: 3,
  score: 5,
  options: [
    { content: '', correct: false },
    { content: '', correct: false }
  ],
  answer: '',
  explanation: ''
})

const rules = {
  title: [
    { required: true, message: '请输入试题标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择题型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入试题内容', trigger: 'blur' }
  ],
  subjectId: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' }
  ]
}

// 初始化表单
const initForm = () => {
  if (props.question) {
    Object.assign(form, {
      ...props.question,
      options: props.question.options || [
        { content: '', correct: false },
        { content: '', correct: false }
      ]
    })
    
    // 设置单选题的正确答案
    if (form.type === 'SINGLE_CHOICE' && form.options) {
      const correctIndex = form.options.findIndex(opt => opt.correct)
      if (correctIndex !== -1) {
        correctAnswer.value = correctIndex
      }
    }
  } else {
    // 重置表单
    Object.assign(form, {
      id: null,
      title: '',
      type: 'SINGLE_CHOICE',
      content: '',
      subjectId: undefined,
      categoryId: undefined,
      difficulty: 3,
      score: 5,
      options: [
        { content: '', correct: false },
        { content: '', correct: false }
      ],
      answer: '',
      explanation: ''
    })
    correctAnswer.value = 0
  }
}

// 添加选项
const addOption = () => {
  if (form.options.length < 6) {
    form.options.push({ content: '', correct: false })
  }
}

// 删除选项
const removeOption = (index: number) => {
  if (form.options.length > 2) {
    form.options.splice(index, 1)
    // 如果删除的是当前选中的正确答案，重置为第一个
    if (form.type === 'SINGLE_CHOICE' && correctAnswer.value >= index) {
      correctAnswer.value = 0
    }
  }
}

// 学科变化处理
const handleSubjectChange = () => {
  form.categoryId = undefined
}

// 监听单选题正确答案变化
watch(correctAnswer, (newVal) => {
  if (form.type === 'SINGLE_CHOICE') {
    form.options.forEach((option, index) => {
      option.correct = index === newVal
    })
  }
})

// 监听对话框显示状态
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const submitData = { ...form }
    
    // 处理不同题型的答案
    if (form.type === 'SINGLE_CHOICE') {
      // 单选题：设置正确答案
      submitData.options.forEach((option, index) => {
        option.correct = index === correctAnswer.value
      })
    } else if (form.type === 'TRUE_FALSE') {
      // 判断题：答案已经在form.answer中
    } else if (['FILL_BLANK', 'ESSAY'].includes(form.type)) {
      // 填空题和问答题：答案在form.answer中
      submitData.options = []
    }
    
    if (isEdit.value) {
      await questionApi.updateQuestion(submitData.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await questionApi.createQuestion(submitData)
      ElMessage.success('创建成功')
    }
    
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.question-form {
  padding: 20px 0;
}

.options-container {
  width: 100%;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.option-checkbox,
.option-radio {
  flex-shrink: 0;
}

.option-input {
  flex: 1;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}
</style>